package com.test.sdk.provider.filter;

import com.test.sdk.pojo.Game;
import com.test.sdk.provider.cache.GameCache;
import com.test.sdk.provider.exception.SdkException;
import com.test.sdk.provider.exception.SdkExceptionHandler;
import com.test.sdk.provider.util.ErrorConstants;
import com.test.sdk.provider.util.RequestUtil;
import com.test.sdk.provider.util.SignUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class GlobalFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String sign = request.getParameter("sign");
        if (sign == null || sign.trim().length() == 0) {
            SdkExceptionHandler.handlerException(request, response, new SdkException(ErrorConstants.PARAM_ERROR));
            return;
        }
        System.out.println(sign);
        Integer cpId = RequestUtil.getInt(request, "cpId");
        //根据cpid去缓存中查询cp的秘钥，当成盐值去计算MD5签名
        String mySign = SignUtil.sign(SignUtil.signStr(request.getParameterMap()));
        System.out.println(mySign);
        if (sign.equals(mySign)) {

            Integer seqNum = RequestUtil.getInt(request, "seqnum");
            Integer prtchid = RequestUtil.getInt(request, "prtchid");
            if (cpId == null || seqNum == null || prtchid == null) {
                SdkExceptionHandler.handlerException(request, response, new SdkException(ErrorConstants.PARAM_ERROR));
                return;
            }
            Game game = GameCache.getGame(cpId, seqNum);
            if (game == null) {
                SdkExceptionHandler.handlerException(request, response, new SdkException(ErrorConstants.GAME_NOT_EXIST));
                return;
            }
            filterChain.doFilter(request, response);
        }else{
            SdkExceptionHandler.handlerException(request, response, new SdkException(ErrorConstants.SIGN_ERROR));
            return;
        }
    }
}
